Add digits

Time: O(1); Space: O(1); easy

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example 1:

Input: num = 38

Output: 2

Explanation:

  • 3 + 8 = 11

  • -> 1 + 1 = 2

Since 2 has only one digit, return it.

Follow up:

Could you do it without any loop/recursion in O(1) runtime?

Hints:

  1. A naive implementation of the above process is trivial. Could you come up with other methods?

  2. What are all the possible results?

  3. How do they occur, periodically or randomly?

  4. You may find this Wikipedia article useful.

[1]:
class Solution1(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        return (num - 1) % 9 + 1 if num > 0 else 0
[2]:
s = Solution1()
num = 38
assert s.addDigits(num) == 2